import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Row, Col, Card, Button, Input, Modal, message, Drawer, Icon, Layout, Spin, } from "antd";
import styles from "./index.less";
import { getAuthority } from "@/utils/judgeAuthority";
import { cancelQaImport, importQACheck } from "@/services/knowledgemanagement";

const LeftTree = React.lazy(() => import("./leftTree"));
const QaList = React.lazy(() => import("./qaList"));
// const EditQa = React.lazy(() => import('./editQa'));
// import ClassifyTree from './ClassifyTree';
const ClassifyTree = React.lazy(() => import("./ClassifyTree"));

const { Header, Content, Footer, Sider } = Layout;
let checkInterval = null
class OverView extends Component {
	constructor(props) {
		super(props);
		this.state = {
			nodeId: "",
			nodeIdName: "所有分类",
			close: false,
			qaId: "",
			isUpdate: false,
			nodePath: "",
			code: "",
			noAnswer: false,
			questionCount: "",
			qaListCz: "",
			classifyTree: {
				loading: true,
				list: [],
			},
			isShard: false,
			loading: true,
			globalLoading: true,
			cancelling: false,
			checkImportMethod: 'init'
		};
	}

	componentDidMount() {
		this.checkImport()
		if (this.props.location.query) {
			const sortType = this.props.location.query.sortType;

			switch (sortType) {
				case "noAnswer":
					this.setState({ noAnswer: true, });
					break;
				case "questionCount":
					this.setState({ questionCount: 3, });
					break;
				default:
					this.setState({ questionCount: "", noAnswer: false, });
			}
		}

		// this.getClass();
	}

	checkImport = async () => {
		const res = await importQACheck({ rootCategoryId: this.props.match.params.id })
		switch (res.data) {
			case 0:
				//没有导入的任务
				this.isShowGlobalLoading(false);
				setTimeout(() => {
					this.LeftTree.fetch(true);
				}, 300);
				clearInterval(checkInterval);
				checkInterval = null;
				this.setState({ cancelling: false });
				break;
			case 1:
				//导入中
				this.isShowGlobalLoading(true)
				if (!checkInterval) {
					checkInterval = setInterval(() => {
						this.checkImport()
					}, 5000)
				};
				this.setState({ cancelling: false });
				break;
			case 2:
				//导入失败
				this.isShowGlobalLoading(false);
				message.error(res.message);
				setTimeout(() => {
					this.LeftTree.fetch(true);
				}, 300);
				clearInterval(checkInterval);
				checkInterval = null;
				this.setState({ cancelling: false });
				break;
			case 3:
				//导入成功
				this.isShowGlobalLoading(false);
				message.info(res.message);
				setTimeout(() => {
					this.LeftTree.fetch(true);
				}, 300);
				clearInterval(checkInterval);
				checkInterval = null;
				this.setState({ cancelling: false });
				break;
			case 4:
				//取消导入中
				this.isShowGlobalLoading(true)
				if (!checkInterval) {
					checkInterval = setInterval(() => {
						this.checkImport()
					}, 5000)
				};
				this.setState({ cancelling: true });
				break;
		}
	}

	qaListPd = (val) => {
		this.setState({ qaListCz: val });
	};

	// ----树形图方法开始----
	terrNodeId = (nodeId, nodeIdName, nodePath, isShard, parentPath, parentId) => {
		this.setState({ nodeId, nodeIdName, nodePath, isShard, parentPath, parentId }, () => {
			this.child.getQaListByFortherCall(nodeId, nodeIdName, nodePath, isShard, parentPath, parentId);
		});
	};

	// 停用启用变更需要刷新列表
	refresh = (code) => {
		this.setState({ code });
	};
	// ----树形图方法结束----

	// 添加
	showDrawer = (id, categoryId, isShard) => {
		this.setState({ qaId: id, close: true, nodePath: categoryId, isShard, });
	};

	onClose = () => {
		this.setState({ close: false, qaId: "", isUpdate: true, });
		this.child.fetchListBySearch();
	};

	getClass = (type) => {
		let { classifyTree } = this.state;
		const { dispatch } = this.props;
		if (type) {
			this.child.fetchListBySearch();
		};
		const that = this;
		// dispatch({
		//   type: 'qaList/categoryListJson',
		//   payload: {},
		//   callback: res => {
		//     classifyTree = { loading: false, list: res, };
		//     that.setState({ classifyTree });
		//   },
		// });
	};

	treeOnClick = (treeData) => {
		let { nodeId, nodePath, nodeIdName } = this.state;
		nodeId = treeData.id;
		nodePath = treeData.data.path;
		nodeIdName = treeData.title;
		this.setState({ nodePath, nodeIdName, nodeId, }, () => {
			this.child.getQaListByFortherCall(nodeId, nodeIdName, nodePath, treeData.isShared);
		});
	};

	leftTreeList = () => {
		this.setState({}, () => {
			this.LeftTree.fetch();
		});
	};

	isShowGlobalLoading = (globalLoading, checkImportMethod) => {
		this.setState({ globalLoading, loading: false, checkImportMethod });
	};

	cancelImport = async () => {
		const { checkImportMethod } = this.state;
		for (let i = 1; i < 100000; i++) {
			clearInterval(i);
		};
		checkInterval = null;
		if (this.child && this.child.setCheckListInterval) {
			this.child.setCheckListInterval(null)
		};
		const res = await cancelQaImport({ rootCategoryId: this.props.match.params.id });
		if (res.data == 0) {
			//取消导入失败
			message.error("取消导入操作失败")
		};
		if (checkImportMethod === 'btn') {
			this.child.checkImport()
		} else {
			this.checkImport()
		};
		// this.setCancelling(true)
	}

	componentWillUnmount() {
		console.log('离开了当前页面');
		clearInterval(checkInterval)
		checkInterval = null
	}

	setCancelling = flag => {
		this.setState({
			cancelling: flag
		})
	}

	render() {
		const { match: { params: { id }, }, route, location: { params } } = this.props;
		const { globalLoading, loading, cancelling } = this.state;

		return (
			<Suspense fallback={<PageLoading />}>
				<Spin
					spinning={globalLoading}
					tip={
						loading ? null : (
							<div>
								<p>{cancelling ? '正在取消导入，请稍等...' : '知识点正在导入，请稍等...'}</p>
								{
									cancelling ? '' : (
										<Button onClick={this.cancelImport} type="primary" size="small">取消导入</Button>
									)
								}
							</div>
						)
					}
				>
					<Layout style={{ minHeight: 'calc(100vh - 64px - 10px - 66px - 20px)' }}>
						<Sider width={260} style={{ background: "#FAFAFA" }} className={styles.siderTree}>
							<Row gutter={16}>
								<Col>
									<LeftTree
										qaListCz={this.state.qaListCz}
										terrNodeId={this.terrNodeId}
										refresh={this.refresh}
										getClass={this.getClass.bind(this)}
										authority={getAuthority(route.authority)}
										onRef={(ref) => (this.LeftTree = ref)}
										getListByTreeRoot={(data) => this.child.getListByTreeRoot(data)}
										categoryId={id}
									/>
								</Col>
							</Row>
						</Sider>
						<Content style={{ borderLeft: "1px solid #E6ECF6", background: '#ffffff' }}>
							<Row gutter={16}>
								<Col>
									<Card bordered={false} bodyStyle={{ paddingTop: 0, paddingBottom: 20 }}>
										<QaList
											id={id}
											qaListPd={this.qaListPd}
											code={this.state.code}
											editQaById={this.showDrawer}
											categoryId={this.state.nodeId}
											nodePath={this.state.nodePath}
											categoryName={this.state.nodeIdName}
											isUpdate={this.state.isUpdate}
											onRef={(ref) => (this.child = ref)}
											noAnswer={this.state.noAnswer}
											sortType={this.state.questionCount}
											isShared={this.state.isShard}
											treeList={this.leftTreeList}
											authority={getAuthority(route.authority)}
											isShowGlobalLoading={this.isShowGlobalLoading}
											urlParams={params}
											setCancelling={this.setCancelling}
										/>
									</Card>
								</Col>
							</Row>
						</Content>
					</Layout>
				</Spin>
				{/*<Drawer*/}
				{/*  title={*/}
				{/*    <span onClick={this.onClose}>*/}
				{/*      <Icon type="left" style={{ marginRight: 10, cursor: 'pointer' }} />*/}
				{/*      {this.state.qaId ? '知识点编辑' : '知识点添加'}*/}
				{/*    </span>*/}
				{/*  }*/}
				{/*  placement="right"*/}
				{/*  closable*/}
				{/*  onClose={this.onClose}*/}
				{/*  visible={this.state.close}*/}
				{/*  width={800}*/}
				{/*  destroyOnClose*/}
				{/*  className={styles.drawer}*/}
				{/*>*/}
				{/*  <EditQa*/}
				{/*    qaId={this.state.qaId}*/}
				{/*    categoryIds={this.state.nodeId}*/}
				{/*    onClose={this.onClose}*/}
				{/*    isShard={this.state.isShard}*/}
				{/*  />*/}
				{/*</Drawer>*/}
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(OverView);
